<?php defined('SYS_PATH') or die('No direct script access.');
/**
 * Config class
 *
 * @author zendzhang<zendzhang@hotmail.com>
 * @version $Id: Config.php 9 2013-01-14 03:24:50Z zendzhang@hotmail.com $
 */
class TrueBlood_Config extends TrueBlood
{
    /**
     * Array of loaded config files
     *
     * @var array
     */
    protected static $_loaded = array();

    /**
     * Array of config values
     *
     * @var array
     */
    protected static $_config = array();

    /**
     * Load config file
     *
     * @param string $file
     * @param bool $overwrite
     * @return bool
     */
    public static function load($file, $overwrite = false)
    {
        if (!$overwrite && in_array($file, self::$_loaded, true))
        {
            return true;
        }
        if (($path = self::$load->findFile(APP_PATH . '/configs/', $file . '.inc.php')) === false)
        {
            throw new TrueBlood_Exception('The configuration file ' . $file . '.inc.php does not exist.');
        }
        require $path;
        if (!isset($config) || !is_array($config))
        {
            throw new TrueBlood_Exception('Your ' . $file . '.inc.php file does not appear to contain a valid configuration array.');
        }
        self::$_config = array_merge(self::$_config, $config);
        self::$_loaded[] = $file;
        unset($config);

        self::log('debug', 'Config file loaded: configs/' . $file . '.inc.php');
        return true;
    }

    /**
     * Fetch a config file item.
     *
     * @param string $name
     * @param mixed $default
     * @param string $delimiter
     * @return mixed
     */
    public static function item($name = null, $default = null, $delimiter = '.')
    {
        if (null === $name)
        {
            return self::$_config;
        }
        if (false === strpos($name, $delimiter))
        {
            return isset(self::$_config[$name]) ? self::$_config[$name] : $default;
        }
        $keys = explode($delimiter, $name);
        $ret = self::$_config;
        foreach ($keys as $key)
        {
            if (!isset($ret[$key]))
            {
                return $default;
            }
            $ret = $ret[$key];
        }
        return $ret;
    }

    /**
     * Magic function so that $obj->value will work.
     *
     * @param string $name
     * @return mixed
     */
    public function __get($name)
    {
        return $this->item($name);
    }
}

?>